package org.lq.us.web.linster;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

import org.lq.us.entity.Users;

import lombok.extern.log4j.Log4j;

/**
 * Application Lifecycle Listener implementation class SingletonUsersLogin
 *
 */
@WebListener
@Log4j
public class SingletonUsersLogin implements HttpSessionAttributeListener {

	//存储以登录用户信息
	private Map<String, HttpSession> map = new HashMap<String, HttpSession>();
  
	/**
     * @see HttpSessionAttributeListener#attributeAdded(HttpSessionBindingEvent)
     */
    public void attributeAdded(HttpSessionBindingEvent event)  { 
    	
    	String name= event.getName();
    	if("user".equals(name)) {
    		Users user = (Users) event.getValue();
    		if(map.get(user.getUserName())!=null) {
    			HttpSession session = map.get(user.getUserName());
    			session.invalidate();
    			log.info("账户 : "+user.getUserName()+"已经登录,该用户被强制下线.");
    		}
    		map.put(user.getUserName(), event.getSession());
    	}
    	
    	
    }

	/**
     * @see HttpSessionAttributeListener#attributeRemoved(HttpSessionBindingEvent)
     */
    public void attributeRemoved(HttpSessionBindingEvent event)  { 
         // TODO Auto-generated method stub
    }

	/**
     * @see HttpSessionAttributeListener#attributeReplaced(HttpSessionBindingEvent)
     */
    public void attributeReplaced(HttpSessionBindingEvent event)  { 
    	String name = event.getName();
    	//没有注销,然后用另一个账户登录
    	if(name.equals("user")) {
    		Users oldUser = (Users) event.getValue();
    		map.remove(oldUser.getUserName());
    		
    		HttpSession session = event.getSession();
    		Users newUser= (Users) session.getAttribute("user");
    		if(map.get(newUser.getUserName())!=null) {
    			map.get(newUser.getUserName()).invalidate();
    		}
    		
    		map.put(newUser.getUserName(),session);
    	}
    }
	
}
